package com.example.petstore_2.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.petstore_2.common.CommonResponse;
import com.example.petstore_2.domain.Item;
import com.example.petstore_2.mapper.ItemMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service("itemService")
public class ItemService {
    @Autowired
    private ItemMapper itemMapper;
    public CommonResponse getItemByItemid(String itemId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("itemid", itemId);
        queryWrapper.eq("isup", 1);
        Item item = itemMapper.selectOne(queryWrapper);
        if(item == null){
            log.warn(itemId + " 获取失败");
            return CommonResponse.creatForError("出错了，请稍后再试");
        }
        log.info(itemId + " 获取成功");
        addViews(itemId);
        return CommonResponse.creatForSuccess(item);
    }

    public CommonResponse getItemByItemidForCart(String itemId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("itemid", itemId);
//        queryWrapper.eq("isup", 1);
        Item item = itemMapper.selectOne(queryWrapper);
        if(item == null){
            log.warn(itemId + " 获取失败");
            return CommonResponse.creatForError("出错了，请稍后再试");
        }
        log.info(itemId + " 获取成功");
        addViews(itemId);
        return CommonResponse.creatForSuccess(item);
    }



    public CommonResponse getItemList() {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("isup", 1);
        List<Item> items = itemMapper.selectList(queryWrapper);
        return CommonResponse.creatForSuccess(items);
    }

    public CommonResponse addViews(String itemid) {
        log.info("用户浏览 " + itemid);
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("itemid", itemid);
        Item item = itemMapper.selectOne(queryWrapper);
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("itemid", itemid);
        updateWrapper.set("views", item.getViews() + 1);
        int result = itemMapper.update(updateWrapper);
        if(result == 1){
            return CommonResponse.creatForSuccess();
        }
        return CommonResponse.creatForError();
    }

    public List<Item> getItemListByProductId(String productId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("productid", productId);
        queryWrapper.eq("isup", 1);
        return itemMapper.selectList(queryWrapper);
    }
}
